import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

let clock = null
let reqCount = 0
const SHOW_LOADING_DELAY = 500

function reqEnd () {
  reqCount--
  if (reqCount < 1) {
    clearTimeout(clock)
    // todo 清除加载中...
  }
}

function reqStart () {
  if (reqCount === 0) {
    clock = setTimeout(() => {
      // todo 加载中...
    }, SHOW_LOADING_DELAY)
  }
  reqCount++
}

Vue.axios.interceptors.request.use((config) => {
  reqStart()

  // 解决get请求缓存问题
  if (config.method && config.method.toLowerCase() === 'get') {
    config.params = config.params || {}
    config.params['_t'] = +new Date()
  }

  return config
}, (err) => {
  reqEnd()
  return Promise.reject(err)
})

Vue.axios.interceptors.response.use(async (res) => {
  reqEnd()

  if (res && res.status === 200) {
    res = res.data
  }
  return res
}, (err) => {
  reqEnd()
  return Promise.reject(err)
})
